package sg.edu.nus.iss.phoenix.users.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

import sg.edu.nus.iss.phoenix.authenticate.entity.Role;
import sg.edu.nus.iss.phoenix.authenticate.entity.User;
import sg.edu.nus.iss.phoenix.users.dao.UserRoleDAO;


/**
 * @author Nishanthan Puwanendran
 *
 */
public class UserRoleDAOImpl  implements UserRoleDAO{
	
	private Connection connection;
	
	/*
	 * (non-Javadoc)
	 * @see sg.edu.nus.iss.phoenix.users.dao.UserRoleDAO#grantAccess(sg.edu.nus.iss.phoenix.authenticate.entity.User, sg.edu.nus.iss.phoenix.authenticate.entity.Role, sg.edu.nus.iss.phoenix.authenticate.entity.User)
	 */
	public void grantAccess(User uservalueObject, Role rolevalueObject, User currentUser) throws SQLException
	{
		String sql_grantrole = "";
		PreparedStatement stmt = null;
		Calendar c = Calendar.getInstance();
		
		try {
			sql_grantrole = "INSERT INTO user_role_mst ( user_id, role_id, created_by,created_dt) "
					+ " VALUES (?, ?, ?, ?) ";
			stmt = this.connection.prepareStatement(sql_grantrole);

			stmt.setString(1, String.valueOf(uservalueObject.getId()));
			stmt.setString(2, String.valueOf(rolevalueObject.getRoleId()));
			stmt.setString(3, currentUser.getName());
			stmt.setString(4, c.getTime().toString());

			stmt.execute();

		} finally {
			if (stmt != null)
				stmt.close();
		}
	
	}
	
	/*
	 * (non-Javadoc)
	 * @see sg.edu.nus.iss.phoenix.users.dao.UserRoleDAO#revokeAccess(sg.edu.nus.iss.phoenix.authenticate.entity.User, sg.edu.nus.iss.phoenix.authenticate.entity.Role)
	 */
	public void revokeAccess(User uservalueObject, Role rolevalueObject) throws SQLException
	{
		String sql_revokerole = "";
		PreparedStatement stmt = null;
		
		try {
			sql_revokerole = "delete from user_role_mst where user_id =? and role_id=?";
			stmt = this.connection.prepareStatement(sql_revokerole);

			stmt.setString(1, String.valueOf(uservalueObject.getId()));
			stmt.setString(2, String.valueOf(rolevalueObject.getRoleId()));

			stmt.execute();

		} finally {
			if (stmt != null)
				stmt.close();
		}
	}
}
